<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="考试名称" prop="className">
        <el-input
          v-model="queryParams.examName"
          placeholder="请输入考试名称"
          clearable
          size="small"
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="考试日期" prop="status">
        <el-date-picker
          v-model="queryParams.examDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="状态" prop="classDept">
        <el-select v-model="queryParams.status" clearable size="small" style="width: 180px">
          <el-option value="0" label="停用"></el-option>
          <el-option value="1" label="启用"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
          <el-button
            type="warning"
            icon="el-icon-circle-check"
            size="mini"
            @click="operationStatus(1)"
            :disabled="multiple"
            >启用</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="el-icon-circle-close"
            size="mini"
            @click="operationStatus(0)"
            :disabled="multiple"
            >停用</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="handleDeleteBatch()"
          :disabled="multiple"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="bclassList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column label="学期" align="center" prop="termRemarks" :show-overflow-tooltip="true" />
      <el-table-column label="考试课程" align="center" prop="dictLabel" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="考试名称" align="center" prop="examName" :show-overflow-tooltip="true" />
      <el-table-column label="考试开始时间" align="center" prop="examBeginTime" width="160"></el-table-column>
      <el-table-column label="考试结束时间" align="center" prop="examEndTime" width="160"></el-table-column>
      <el-table-column label="监考老师" align="center" prop="invigilationTeacher" width="160"></el-table-column>
      <el-table-column label="考试教室" align="center" prop="levelName" width="160"></el-table-column>
      <el-table-column label="通过人数" align="center" prop="pass" width="80"></el-table-column>
      <el-table-column label="未通过人数" align="center" prop="noPass" width="100"></el-table-column>
      <el-table-column label="通过率" align="center" prop="noPass" width="100">
        <template slot-scope="scope">{{getPercent(scope.row.pass,scope.row.count) + '%'}}</template>
      </el-table-column>

      <el-table-column label="平均分" align="center" prop="avgScore" width="80"></el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            circle
            type="success"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="考试名称" prop="examId">
            <el-select
              v-model="form.examId"
              placeholder="请选择考试"
              filterable
              clearable
              @change="selectExam"
              style="width:50%"
            >
              <el-option
                v-for="item in examOptions"
                :key="item.id"
                :value="item.id"
                :label="item.examName"
              >
                <span style="float: left">{{ item.examName }}</span>
                <span
                  style="float: right; color: #8492a6; font-size: 13px"
                >考试时间：{{ item.examBeginTime }} ~ {{ item.examEndTime }}</span>
              </el-option>
            </el-select>
            <el-button type="success" size="small"  v-if="form.examId"  class="el-icon-download" @click="exportTemplate">导出模板</el-button>
            <el-upload
                style="width:100px;display: contents;"
                ref="upload"
                name="upload"
                class="upload-demo"
                :action="upload.url"
                :headers="upload.headers"
                :before-upload="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-success="handleFileSuccess"
                :show-file-list="false"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList">
                <el-button type="primary" size="small" v-if="form.examId" class="el-icon-upload2" :loading="importLoading">上传成绩</el-button>
              </el-upload>
          </el-form-item>
        <el-form-item v-if="examItem.className">
          <label>考试班级:</label>
          <el-link type="primary" :underline="false">{{examItem.className}}</el-link>
          <label>考试课程:</label>
          <el-link type="primary" :underline="false">{{examItem.dictLabel}}</el-link>
          <label>考试开始时间:</label>
          <el-link type="primary" :underline="false">{{examItem.examBeginTime}}</el-link>
          <label>考试结束时间:</label>
          <el-link type="primary" :underline="false">{{examItem.examEndTime}}</el-link>
        </el-form-item>
        <!-- <el-form-item>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              
            </el-col>
            <el-col :span="1.5">
              
            </el-col>
          </el-row>
        </el-form-item> -->
        <el-form-item v-if="examItem.className" label="考试名单">
          <el-table :data="form.examStudents">
            <el-table-column label="序号" align="center" type="index" />
            <el-table-column label="学生姓名" align="center" prop="studentName" />
            <el-table-column label="学号" align="center" prop="studentCode" />
            <el-table-column label="考试分数" align="center" prop="score">
              <template slot-scope="scope">
                <el-input v-model="scope.row.score" placeholder="分数"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="是否通过" align="center" prop="isPass">
              <template slot-scope="scope">
                <el-radio v-model="scope.row.isPass" label="0">不通过</el-radio>
                <el-radio v-model="scope.row.isPass" label="1">通过</el-radio>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import {
  editExam,
  deleteExam,
  deleteBatchExam,
  updateBatchExam
} from "@/api/studentInfo/examManage";
import {
  queryExam,
  queryClassStudents,
  editExamResult,
  pageList,
  queryExamResult,
  deleteBatch,
  exportExamResultTemplateByClassId
} from "@/api/studentInfo/examResultEnter";
import { getClassTeacherList } from "@/api/system/user";
import { getToken } from '@/utils/auth'


export default {
  name: "BClass",
  data() {
    return {
      importLoading:false,
      upload:{
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/exam/result/importExamResult",
      },
      fileList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      rowList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      stuCount: 0,
      // 字典表格数据
      bclassList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 班主任
      userOptions: [],
      // 状态数据字典
      statusOptions: [],
      // 班级所属部门
      classDeptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        className: undefined,
        status: undefined,
        classDept: undefined
      },
      // 表单参数
      form: {
        examId: undefined,
        examStudents: []
      },
      // 表单校验
      rules: {
        examId: [{ required: true, message: "请选择考试名称", trigger: "blur" }]
      },
      examOptions: [],
      examItem: {},
      classStudents: [],
    };
  },
  created() {
    this.getList();
    this.getExamList();
  },
  methods: {
    exportTemplate(){
      let obj = this.examItem
      this.$confirm('是否导出当前班级的考试成绩录入模板?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
          return exportExamResultTemplateByClassId(obj.classId);
      }).then(response => {
          this.fileDownload(response.data, obj.className + "考试成绩录入模板.xlsx");
        }).catch(function() {});
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    handlePreview(file) {
      // console.log(file);
      this.importLoading = true
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    // 更新导入文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.form.examStudents = [];
      for (let i = 0; i < response.data.length; i++) {
        this.form.examStudents.push({
          score: response.data[i].score,
          isPass: response.data[i].isPass,
          studentCode: response.data[i].studentCode,
          studentName: response.data[i].studentName,
        });
      }
      this.importLoading = false
      this.msgSuccess("成绩上传成功");
      this.fileList = [];
      // console.log(this.form)
    },
    getPercent(num, total) {
      //计算百分比
      num = parseFloat(num);
      total = parseFloat(total);
      if (isNaN(num) || isNaN(total)) {
        return 0;
      }
      return total <= 0 ? "0%" : Math.round((num / total) * 10000) / 100.0;
    },
    getClassStudent(classIdParam) {
      this.form.examStudents = [];
      queryClassStudents({ classId: classIdParam }).then(resp => {
        for (let i = 0; i < resp.data.length; i++) {
          this.form.examStudents.push({
            score: "0",
            isPass: "0",
            studentCode: resp.data[i].studentId,
            studentClassId: resp.data[i].classId,
            studentName: resp.data[i].name,
            studentClassName: resp.data[i].className
          });
        }
        // this.classStudents=resp.data
        // console.log(resp);
      });
    },
    selectExam(value) {
      // console.log(value);
      this.examItem = this.examOptions.find(function(item) {
        // console.log(item);
        return item.id == value;
      });
      // console.log(this.examItem);
      this.getClassStudent(this.examItem.classId);
    },
    getExamList(val) {
      const dateTime = this.parseTime(new Date().getTime());
      queryExam({
        pageSize: 1000,
        pageNum: 0,
        examName: val,
        examEndTime: dateTime
      }).then(resp => {
        this.examOptions = resp.data;
      });
    },
    /** 查询班级列表 */
    getList() {
      this.loading = true;
      pageList(this.queryParams).then(response => {
        this.bclassList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    getClassTeacherList() {
      getClassTeacherList().then(response => {
        this.userOptions = response.data;
      });
    },
    // 字典设备状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 字典设备状态字典翻译
    classDeptFormat(row, column) {
      return this.selectDictLabel(this.classDeptOptions, row.classDept);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        className: undefined,
        classTeacherId: undefined,
        status: "1",
        classDept: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加班级信息";
      this.examItem = {};
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // console.log(selection);
      this.rowList = selection;

      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = ''
      this.reset();
      this.fileList = [];
      this.open = true;
      console.log(this.examOptions)
      this.examItem = this.examOptions.find(function(item) {
        // console.log(item);
        return item.id == row.id;
      });
      console.log(this.examItem)
      this.form.examStudents = [];
      this.form.examId = row.id;

      queryExamResult({ examId: row.id }).then(resp => {
        const list = resp.data;
        this.form.id = list[0].id;
        if (list.length > 0) {
          // this.form.examId = Number(list[0].examId)
          // console.log(this.form.examId);
          for (let i = 0; i < list.length; i++) {
            this.form.examStudents.push({
              score: list[i].score,
              isPass: list[i].isPass,
              studentCode: list[i].studentCode,
              studentClassId: list[i].studentClassId,
              studentName: list[i].studentName,
              studentClassName: list[i].studentClassName
            });
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          editExamResult(this.form).then(resp => {
            this.msgSuccess("提交成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return deleteExam(row);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },

    // 获取当前选中班主任的名称
    selectUser(val) {
      alert(val.label);
      this.form.username = val.label;
    },
    operationStatus(flag) {
      //修改状态
      let str = "启用";
      if (flag == 0) {
        str = "停用";
      }
      for (let i = 0; i < this.rowList.length; i++) {
        this.rowList[i].status = flag;
      }
      updateBatchExam(this.rowList).then(resp => {
        this.msgSuccess(str + "成功");
        this.getList();
      });
    },
    handleDeleteBatch() {
      //批量删除
      this.$confirm("是否确认删除选择的数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteBatch(this.rowList).then(resp => {
            this.getList();
            this.msgSuccess("删除成功");
          });
        })
        .catch(function() {});
    }
  }
};
</script>
  